<?php

namespace app\api\controller;

use app\admin\model\system\System;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Exchange extends Api{
    protected $noNeedLogin = ['getrate'];
    protected $noNeedRight = ['*'];

    public function getrate(){
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $this->success('成功',['rate'=>$systeminfo['new_bili']]);
    }

    public function exchange(){
        $amount = $this->request->post('amount');
        $userinfo = $this->auth->getUserinfo();
        if($amount>$userinfo['shouyi_balance']){
            $this->error('余额不足');
        }
        if($userinfo['is_freeze']==1){
            $this->error('您的帐户被冻结，不能闪兑');
        }
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $exchange_amount=$amount/$systeminfo['bili'];

        $exchangeModel = new \app\admin\model\exchange\Exchange();
        $userModel = new \app\admin\model\User();
        Db::startTrans();
        try{
            //修改用户余额
            $userModel->where(['id'=>$userinfo['id']])->update([
                'shouyi_balance'=>$userinfo['shouyi_balance']-$amount,
                'usdt_balance'=>$userinfo['usdt_balance']+$exchange_amount,
            ]);

            //写入况换纪录
            $indata['amount'] = $amount;
            $indata['bili'] = $systeminfo['bili'];
            $indata['exchange_amount'] = $exchange_amount;
            $indata['user_id'] = $userinfo['id'];
            $indata['create_time'] = time();
            $exchangeModel->insert($indata);

            Db::commit();
            $this->success('闪兑成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function mylist(){
        $userinfo = $this->auth->getUserinfo();
        $exchangeModel = new \app\admin\model\exchange\Exchange();
        $list = collection($exchangeModel->where(['user_id'=>$userinfo['id']])->order('create_time desc')->select());
        if($list){
            $list = $list->toArray();
            $newlist=[];
            foreach ($list as $k=>$v){
                $newlist[$k]['id']=$v['id'];
                $newlist[$k]['amount']=$v['amount'];
                $newlist[$k]['bili']=$v['bili'];
                $newlist[$k]['exchange_amount']=$v['exchange_amount'];
                $newlist[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
            }
            $this->success('成功',$newlist);
        }else{
            $this->success('成功',[]);
        }
    }
}
